// 股票分析功能模块
import { loadConfig } from './config.js';
import { showError, updateAnalysisResult, renderBatchResults } from './resultHandler.js';

/**
 * 获取当天有买入/卖出信号的股票
 * @param {number} page - 当前页码
 * @param {number} perPage - 每页显示数量
 * @param {string} sortBy - 排序字段
 * @param {string} order - 排序方向 ('asc' 或 'desc')
 * @returns {Promise<Object>} 包含股票数据和分页信息的对象
 */
export async function fetchStocksWithSignals(page = 1, perPage = 20, sortBy = 'symbol', order = 'asc') {
    try {
        // 显示加载状态
        const signalsLoading = document.getElementById('signalsLoading');
        if (signalsLoading) {
            signalsLoading.classList.remove('hidden');
        }
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: page.toString(),
            per_page: perPage.toString(),
            sort_by: sortBy,
            order: order
        });
        
        const response = await fetch(`/api/stocks/signals?${params}`);
        
        if (!response.ok) {
            throw new Error(`获取信号股票失败: ${response.statusText}`);
        }
        
        const data = await response.json();
        
        // 隐藏加载状态
        if (signalsLoading) {
            signalsLoading.classList.add('hidden');
        }
        
        return {
            stocks: data.results || [],
            pagination: data.pagination || {
                page: 1,
                per_page: 20,
                total: 0,
                total_pages: 0
            }
        };
    } catch (error) {
        // 隐藏加载状态
        const signalsLoading = document.getElementById('signalsLoading');
        if (signalsLoading) {
            signalsLoading.classList.add('hidden');
        }
        
        console.error('获取信号股票失败:', error);
        throw error;
    }
}

/**
 * 初始化进度条显示
 * @param {string} symbol 股票代码
 * @param {string} step 初始步骤文本
 */
function initProgressBar(symbol, step = '准备开始分析...') {
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressPercentage = document.getElementById('progressPercentage');
    const progressStep = document.getElementById('progressStep');
    const progressSymbol = document.getElementById('progressSymbol');
    
    progressContainer.classList.remove('hidden');
    progressBar.style.width = '0%';
    progressPercentage.textContent = '0%';
    progressSymbol.textContent = symbol;
    progressStep.textContent = step;
}

/**
 * 更新进度条
 * @param {number} percentage 百分比值 (0-100)
 * @param {string} step 步骤文本
 */
function updateProgressBar(percentage, step) {
    document.getElementById('progressBar').style.width = percentage + '%';
    document.getElementById('progressPercentage').textContent = percentage + '%';
    document.getElementById('progressStep').textContent = step;
}

/**
 * 隐藏进度条（带延迟）
 * @param {number} delay 延迟时间（毫秒）
 */
function hideProgressBarWithDelay(delay = 3000) {
    setTimeout(() => {
        document.getElementById('progressContainer').classList.add('hidden');
    }, delay);
}

/**
 * 分析单只股票
 * @param {string} symbol 股票代码
 */
export async function analyzeStock(symbol) {
    if (!symbol || symbol.trim() === '') {
        showError('请输入股票代码！');
        return;
    }

    symbol = symbol.trim().toUpperCase();

    // 隐藏批量结果，显示进度条
    document.getElementById('batchResultContainer').classList.add('hidden');
    document.getElementById('resultContainer').classList.remove('hidden');
    
    // 初始化进度条
    initProgressBar(symbol);
    
    // 显示加载状态
    document.getElementById('resultAnalysis').innerHTML = '<p class="text-neutral-500"><i class="fa fa-spinner fa-spin mr-2"></i>正在分析中，请稍候...</p>';
    
    // 定期轮询分析状态，使用更频繁的更新
    let statusPolling;
    try {
        // 初始进度更新
        updateProgressBar(10, '准备分析数据...');
        
        statusPolling = setInterval(async () => {
            try {
                const response = await fetch('/api/analysis/status');
                const status = await response.json();
                
                // 确保状态与当前分析的股票匹配
                if (status.symbol === symbol && status.status === 'processing') {
                    // 如果后端返回了进度，则使用后端进度
                    if (status.percentage > 0) {
                        updateProgressBar(status.percentage, status.step || '处理中...');
                    }
                }
            } catch (error) {
                console.error('获取分析状态失败:', error);
            }
        }, 300); // 提高轮询频率到300ms

        // 获取分析结果
        const response = await fetch('/api/stocks/' + symbol);
        const data = await response.json();
        
        // 停止轮询
        clearInterval(statusPolling);
        
        // 显示完成状态
        updateProgressBar(100, '分析完成');
        
        // 3秒后隐藏进度条
        hideProgressBarWithDelay();
        
        if (data.error) {
            showError(data.error);
            document.getElementById('resultAnalysis').innerHTML = '<p>分析失败，请检查股票代码是否正确。</p>';
            return;
        }

        // 更新页面数据
        updateAnalysisResult(data);
    } catch (error) {
        // 停止轮询并处理错误
        if (statusPolling) {
            clearInterval(statusPolling);
        }
        
        document.getElementById('progressContainer').classList.add('hidden');
        
        console.error('分析股票失败:', error);
        showError('分析股票时出错！');
        document.getElementById('resultAnalysis').innerHTML = '<p>分析过程中发生错误，请稍后重试。</p>';
    }
}

/**
 * 批量分析股票
 */
export async function analyzeStocksBatch() {
    try {
        const config = await loadConfig();
        const symbols = config.stock_symbols || [];
        
        if (symbols.length === 0) {
            showError('请先在配置中添加监控股票！');
            return;
        }

        // 隐藏单只结果，显示批量结果容器
        document.getElementById('resultContainer').classList.add('hidden');
        document.getElementById('batchResultContainer').classList.remove('hidden');
        
        // 初始化进度条
        initProgressBar(symbols.join(', '), '准备批量分析...');
        
        // 清空之前的结果
        document.getElementById('batchResults').innerHTML = '';

        // 定期轮询分析状态
        let statusPolling;
        try {
            statusPolling = setInterval(async () => {
                try {
                    const response = await fetch('/api/analysis/status');
                    const status = await response.json();
                    
                    if (status.status === 'processing') {
                        updateProgressBar(
                            status.percentage, 
                            `分析 ${status.symbol || ''}: ${status.step || '处理中...'}`
                        );
                    }
                } catch (error) {
                    console.error('获取分析状态失败:', error);
                }
            }, 500);
            
            // 调用批量分析API
            const response = await fetch('/api/stocks/batch', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ symbols: symbols })
            });
            
            const results = await response.json();
            
            // 停止轮询
            clearInterval(statusPolling);
            
            // 显示完成状态
            updateProgressBar(100, '批量分析完成');
            
            // 3秒后隐藏进度条
            hideProgressBarWithDelay();
            
            // 渲染批量分析结果
            renderBatchResults(results);
        } catch (error) {
            if (statusPolling) {
                clearInterval(statusPolling);
            }
            
            throw error;
        }
    } catch (error) {
        document.getElementById('progressContainer').classList.add('hidden');
        
        console.error('批量分析失败:', error);
        showError('批量分析时出错！');
    }
}